/*
 * utility.h
 *
 *  Created on: 8 Nov 2017
 *      Author: Standa
 */

#ifndef UTILITY_H_
#define UTILITY_H_

#include <stdint.h>
#include "error.h"


#define UT_ISNAN(x)			        ( (x) != (x) )
#define UT_SIZEOFARRAY(x)		    ( sizeof( (x) ) / sizeof( (x[0]) ) )
#define UT_VALINRANGE(val,min,max)  ( ( val >= (min) ) && ( val <= (max) ) )
#define UT_SATURATE(val, min, max)	if( (val) > (max) ){ (val) = (max); }\
									else if( (val) < (min) ){ (val) = (min); }
#define UT_SAFEASSIGN(ptr,val)		if( (ptr) ){ ( *(ptr) = (val) ); };


typedef struct{
	float Mean;
	float Stdev;
	uint32_t Cnt;
	float M2;
}ut_MeanStdevTd;



extern void ut_InitializeOnlineMeanStdev(ut_MeanStdevTd* result);
extern void ut_CalculateOnlineMeanStdev(float newValue, ut_MeanStdevTd* result);

extern float ut_DegToRad(float deg);
extern float ut_RadToDeg(float rad);

extern uint16_t ut_ConvFloatToEngStr(float val, char *dest, char *temp, uint8_t maxLen, uint8_t decCnt);

/*
 * Structure always keeps both Cartesian and Polar representations updated and correct
 */
typedef struct{
	float Real;
	float Imaginary;
	float Magnitude;
	float Angle;
}ut_CplxTd;


extern err_Td ut_CplxReset(ut_CplxTd *v);
extern err_Td ut_CplxInitByRI(ut_CplxTd *c, float real, float imaginary);
extern err_Td ut_CplxInitByMA(ut_CplxTd *c, float magnitude, float angle);
//extern err_Td ut_CplxAdd(ut_CplxTd *cResult, ut_CplxTd *c1, ut_CplxTd *c2);
extern err_Td ut_CplxSub(ut_CplxTd *cResult, ut_CplxTd *c1, ut_CplxTd *c2);
extern err_Td ut_CplxMul(ut_CplxTd *cResult, ut_CplxTd *c1, ut_CplxTd *c2);
extern err_Td ut_CplxDiv(ut_CplxTd *cResult, ut_CplxTd *c1, ut_CplxTd *c2);
extern err_Td ut_CplxScaleM(ut_CplxTd *c, float magScale);


#endif /* UTILITY_H_ */
